#include <iostream>
#include <sstream>

#include <QMessageBox>
#include "widget.h"


using namespace std;

DemoWidget::DemoWidget(QWidget* parent) :
    QWidget(parent),
    ui(new Ui::HelloWidget)
{
    ui->setupUi(this);
}

DemoWidget::~DemoWidget()
{
    delete ui;
}

void DemoWidget::on_calButton_clicked()
{
    printf("Press calButton\n");
    // QMessageBox::information(this, "title", "on_myRadioButton_clicked");
    auto readStr = readTextEdit();
    int result;
    QString text;
    if (!calculate(readStr, result))
    {
        text = "Error";
    }
    else
    {
        text = QString::number(result);
    }
    output(text);
}


string DemoWidget::readTextEdit()
{
    // std::__cxx11::string
    auto input = ui->textEdit->toPlainText().toStdString();
    return input; 
}

void DemoWidget::output(QString &text)
{
    ui->textBrowser->setPlainText(text);
}

bool DemoWidget::calculate(const std::string &expression, int &result) 
{
    std::istringstream iss(expression);
    char op;

    iss >> result;
    while (iss >> op) {
        int num;
        iss >> num;
        result = performOperation(op, result, num);
    }

  return true;
}

int DemoWidget::performOperation(char op, int a, int b) 
{
  switch (op) {
      case '+': return a + b;
      case '-': return a - b;
      case '*': return a * b;
      case '/': return a / b;
  }
  return 0;
}

